<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { adminLogin } from '@/api/index.js'
import { useUserStore } from '@/stores/user.js'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const username = ref('')
const password = ref('')
const rememberMe = ref(false)
const showPassword = ref(false)
const errorMessage = ref('')
const isLoading = ref(false)

// 页面加载时从localStorage读取用户名
onMounted(() => {
  // 检查路由参数中是否有错误信息
  if (route.params.error) {
    errorMessage.value = route.params.message || '登录失败，请重试'
  }

  // 如果已经登录，直接跳转到首页
  if (userStore.loggedIn) {
    router.push('/')
    return
  }

  // 读取用户名（如果启用了记住我）
  const savedUsername = localStorage.getItem('username')
  if (savedUsername) {
    username.value = savedUsername
    rememberMe.value = true
  }
})

function togglePassword() {
  showPassword.value = !showPassword.value
}

async function handleLogin() {
  // 表单验证
  if (!username.value || !password.value) {
    errorMessage.value = '请输入账号和密码'
    return
  }
  
  console.log('开始登录请求，用户名:', username.value)
  
  // 设置加载状态
  isLoading.value = true
  errorMessage.value = ''
  
  try {
    // 调用API登录接口
    console.log('发送登录请求...')
    const response = await adminLogin(username.value, password.value)
    console.log('登录成功，响应数据:', response)
    
    // 使用Pinia存储登录信息
    userStore.setLoginInfo({
      token: response.token,
      admin: response.admin
    })
    
    // 如果需要记住用户名
    if (rememberMe.value) {
      localStorage.setItem('username', username.value)
    } else {
      localStorage.removeItem('username')
    }
    
    // 登录成功，跳转到仪表盘页面
    router.push('/dashboard')
  } catch (error) {
    console.error('登录失败:', error)
    
    // 详细记录错误信息
    if (error.response) {
      console.error('错误状态码:', error.response.status)
      console.error('错误响应数据:', error.response.data)
      
      const errData = error.response.data || {}
      // 处理不同的错误码
      switch (error.response.status) {
        case 400:
          errorMessage.value = errData.message || '请求参数错误，请检查输入格式'
          break
        case 401:
          errorMessage.value = errData.message || '用户名或密码错误，请重试'
          break
        case 403:
          errorMessage.value = errData.message || '账号已被禁用，请联系管理员'
          break
        case 500:
          errorMessage.value = errData.message || '服务器内部错误，请稍后再试'
          break
        default:
          errorMessage.value = errData.message || `登录失败(${error.response.status})，请重试`
      }
    } else if (error.request) {
      // 请求发送但没有收到响应
      console.error('未收到响应:', error.request)
      errorMessage.value = '服务器连接失败，请确认服务器已启动并且网络连接正常'
    } else if (error.message && error.message.includes('Network Error')) {
      // 网络错误
      console.error('网络错误:', error.message)
      errorMessage.value = '网络连接错误，请检查网络设置或服务器状态'
    } else {
      // 请求设置时发生错误
      console.error('其他错误:', error.message)
      errorMessage.value = `登录请求错误: ${error.message}`
    }
  } finally {
    // 无论成功或失败，都关闭加载状态
    isLoading.value = false
  }
}
</script>

<template>
  <div class="bg-gray-100 min-h-screen flex items-center justify-center">
    <div class="container mx-auto">
      <div class="max-w-md mx-auto bg-white rounded-xl shadow-md overflow-hidden md:max-w-2xl">
        <div class="md:flex">
          <div class="p-8 w-full">
            <div class="flex justify-center mb-6">
              <img class="h-14" src="@/assets/logo.svg" alt="商城LOGO">
            </div>
            <div class="text-center mb-8">
              <h2 class="text-2xl font-bold text-gray-800">微信商城后台管理系统</h2>
              <p class="text-gray-500 mt-1">管理员登录</p>
            </div>
            
            <form @submit.prevent="handleLogin">
              <div class="mb-4">
                <label for="username" class="block text-gray-700 font-medium mb-2">管理员账号</label>
                <div class="relative">
                  <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <i class="bi bi-person-badge text-gray-400"></i>
                  </div>
                  <input id="username" v-model="username" type="text" 
                    class="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md leading-5 bg-white placeholder-gray-500 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" 
                    placeholder="请输入管理员账号" required>
                </div>
              </div>
              
              <div class="mb-6">
                <label for="password" class="block text-gray-700 font-medium mb-2">密码</label>
                <div class="relative">
                  <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <i class="bi bi-lock text-gray-400"></i>
                  </div>
                  <input id="password" v-model="password" :type="showPassword ? 'text' : 'password'" 
                    class="block w-full pl-10 pr-10 py-2 border border-gray-300 rounded-md leading-5 bg-white placeholder-gray-500 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" 
                    placeholder="请输入密码" required>
                  <div class="absolute inset-y-0 right-0 pr-3 flex items-center">
                    <i @click="togglePassword" :class="[showPassword ? 'bi-eye-slash' : 'bi-eye', 'text-gray-400 cursor-pointer']"></i>
                  </div>
                </div>
              </div>
              
              <div class="flex items-center justify-between mb-6">
                <div class="flex items-center">
                  <input id="remember-me" v-model="rememberMe" type="checkbox" class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded">
                  <label for="remember-me" class="ml-2 block text-sm text-gray-700">记住我</label>
                </div>
                <div class="text-sm">
                  <a href="#" class="text-indigo-600 hover:text-indigo-500">忘记密码?</a>
                </div>
              </div>
              
              <div class="mb-4">
                <button 
                  type="submit" 
                  class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                  :disabled="isLoading"
                >
                  <span v-if="isLoading" class="inline-block mr-2">
                    <i class="bi bi-arrow-repeat animate-spin"></i>
                  </span>
                  {{ isLoading ? '登录中...' : '管理员登录' }}
                </button>
              </div>
            </form>
            
            <div v-if="errorMessage" class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert">
              <span class="block sm:inline">{{ errorMessage }}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="mt-4 text-center text-gray-500 text-sm">
        © {{ new Date().getFullYear() }} 微信商城后台管理系统 版权所有
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 引入Tailwind和Bootstrap的样式已经足够，不需要额外的样式 */
.animate-spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style> 